﻿using System;
using System.ServiceModel;

namespace Util
{
    public abstract class RemoteConnection<T> : IDisposable where T : class
    {
        private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(5);

        protected ChannelFactory<T> ChannelFactory { get; private set; }

        public T Channel { get; private set; }

        protected abstract ChannelFactory<T> CreateFactory(string uri, TimeSpan timeout);

        protected RemoteConnection(string uri, TimeSpan? timeout)
        {
            ChannelFactory = CreateFactory(uri, timeout ?? DefaultTimeout);
            Channel = ChannelFactory.CreateChannel();
        }

        public void Dispose()
        {
            try
            {
                var disposable = ChannelFactory as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                    ChannelFactory = null;
                }

                disposable = Channel as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                    Channel = null;
                }
            }
            catch (Exception)
            {
                // :(
            }
        }
    }
}
